//
//  HWHomeInfoDetailVC.swift
//  HWanGame
//
//  Created by Apple on 2024/8/7.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import Stevia
import IQKeyboardManagerSwift
import WebKit

class HWHomeInfoDetailVC: HWBaseViewController, WKNavigationDelegate {

    private let scrollView = UIScrollView()
    private let containerView = UIView()
    private var shareButton:UIButton!
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(17.font_semiBold).line(0).end()
    private let userView = c_make_ex(UIView.self)
        .bgColor("#EDEEF0").corner(12*widthScale).end()
    private let userImageView = c_make_ex(UIImageView.self)
        .corner(18*widthScale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(13.font_medium).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#808080").font(11.font_medium).end()
    private let contentWebView = WKWebView()
    private let gameView = c_make_ex(UIView.self)
        .bgColor("#47494D").corner(16*widthScale).end()
    private let gameImageView = c_make_ex(UIImageView.self)
        .corner(12*widthScale).mode(.scaleAspectFill).end()
    private let gameNameLab = c_make_ex(UILabel.self)
        .color("#E4E5E6").font(16.font_semiBold).end()
    private let gameNameTagLab = c_make_ex(UILabel.self)
        .bgColor("#FF7600").corner(4*widthScale)
        .color(.black).font(10.font_semiBold)
        .alignment(.center).text("游戏详情").end()
    private let subLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(10.font_semiBold).end()
    private let gameContentLabel = c_make_ex(UILabel.self)
        .color("#E4E5E6").font(12.font_medium).line(3).end()
    private let headingLabel = c_make_ex(UILabel.self)
        .color("#1A1A1A").font(14.font_semiBold)
        .text("大家都在玩").end()
    private let yqwView = HWHomeInfoDetailGameView()
    private let bottomView = HWHomeInfoDetailBottomView()
    private let commitView = HWHomeInfoDetailCommitView()
    private let commitListView = HWHomeInfoCommitView()
    var gameModel: HWHomeInfoDetailDataModel?
    var infoGameModel: HWHomeInfoDetailGameModel?
    
    private var gid = ""
       
    var infoId = 0 {
        didSet{
            loadData()
            loadCommitListData()
        }
    }
    
    private var httpManager = HWHomeHttpManager()
    private var commitIndex = 1
    private var commitListData = [HWInfoCommentListModel]()
    
    private var isLiked = false
    var loadListData: (() -> Void)?
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isLiked {
            loadListData?()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationView.titleLabel.text = "资讯详情"
        navigationView.backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        view.backgroundColor = "#F7F8FA".toColor

        shareButton = UIButton(type: .custom)
        shareButton.setImage(UIImage(named: "New_share"), for: .normal)
        shareButton.addTarget(self, action: #selector(clickShareButton), for: .touchUpInside)
        navigationView.addSubview(shareButton)
        
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
        contentWebView.navigationDelegate = self
        containerView.translatesAutoresizingMaskIntoConstraints = false
        containerView.isUserInteractionEnabled = false
//        containerView.isActive = true
        
        setupUI()
        
        // 注册键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    
    private func loadData() {
        
        httpManager.getHomeInfoDetail(id: infoId) { infoModel in
            
            guard let dataM = infoModel.data else {
                return
            }
            if let authorM = infoModel.author {
                self.userImageView.sd_setImage(with: URL(string: authorM.avatar))
                self.nameLabel.text = authorM.user_name
                self.userView.heightConstraint?.constant = 55*widthScale
            }else{
                self.userView.heightConstraint?.constant = 0
            }
            if let gameM = infoModel.game {
                
                self.infoGameModel = gameM
                self.gameView.heightConstraint?.constant = 145
                self.gameImageView.sd_setImage(with: URL(string: gameM.icon))
                self.gameNameLab.text = gameM.name
                self.subLabel.text = "类型: " + gameM.system_type_text + " | 人气: " + "\(gameM.number)"
                self.gameContentLabel.text = gameM.content
            } else{
                self.gameView.heightConstraint?.constant = 0
            }
            
            if let yqw = infoModel.game_yqw {
                self.yqwView.dataSource = yqw
            }
            
            self.gameModel = dataM
            self.titleLabel.text = dataM.title
            
            self.timeLabel.text = dataM.time_format
            self.loadHTML(htmlString: dataM.content)
            self.gid = "\(dataM.id)"
            self.bottomView.model = dataM
            
        } failure: { error in
            
        }
    }
    
    private func loadCommitListData(){
        commitIndex = 1
        self.httpManager.getInfoCommitList(infoId: "\(infoId)", p: commitIndex) { models in
            
            self.commitListData.removeAll()
            self.commitListData = models
            self.commitListView.models = models
            if models.count > 0 {
                self.commitListView.isHidden = false
                let md = models[0]
                let height = self.getTextHeigh(textStr: md.content, font: 15.font_medium!, width: screenWidth-104*widthScale) + 110.0
                self.commitListView.heightConstraint?.constant = height + 90
            } else {
                self.commitListView.isHidden = true
                self.commitListView.heightConstraint?.constant = 0
            }
        } failure: { error in
//            self.view.showHUD(title: error)
        }
    }
    
    private func loadMoreCommitListData() {
        commitIndex += 1
        self.httpManager.getInfoCommitList(infoId: "\(infoId)", p: commitIndex) { models in
            
            self.commitListData.append(contentsOf: models)
            self.commitListView.models = self.commitListData
        } failure: { error in
//            self.view.showHUD(title: error)
        }
    }
    
    private func like(type: String, pid: String){
        
        self.httpManager.infoLike(type: type, id: pid) { models in
            
            if type == "0" {
                self.isLiked = true
                self.bottomView.likeButton.isSelected = !self.bottomView.likeButton.isSelected
            }
        } failure: { error in
            self.view.showHUD(title: error)
        }
    }
    
    private func collect(id: String){

        self.httpManager.infoCollect(id: id) { models in
            self.bottomView.collectButton.isSelected = !self.bottomView.collectButton.isSelected
        } failure: { error in
            self.view.showHUD(title: error)
        }

    }

    private func setupUI() {
        
        view.subviews{
            scrollView.subviews{
                containerView.subviews{
                    titleLabel
                    userView.subviews{
                        userImageView
                        nameLabel
                        timeLabel
                    }
                    contentWebView
                    gameView.subviews{
                        gameImageView
                        gameNameLab
                        gameNameTagLab
                        subLabel
                        gameContentLabel
                    }
                    headingLabel
                    yqwView
                    commitListView
                }
            }
            bottomView
            commitView
        }
        
        scrollView.backgroundColor = .clear
        containerView.backgroundColor = .clear
        scrollView.top(.navi_height).leading(0).width(.screenWidth).bottom(82*widthScale)
        containerView.fillContainer().width(.screenWidth)
        bottomView.leading(0).width(.screenWidth).height(82*widthScale).bottom(0)
        commitView.leading(0).width(.screenWidth).height(47*widthScale).bottom(.safe_bottom)
        titleLabel.leading(12*widthScale).trailing(12*widthScale).top(12*widthScale)
        userView.leading(12*widthScale).trailing(12*widthScale).height(55*widthScale)
        userView.Top == titleLabel.Bottom + 20*widthScale
        userImageView.leading(16*widthScale).size(36*widthScale).centerVertically()
        nameLabel.leading(62*widthScale).trailing(90*widthScale)
        nameLabel.Top == userImageView.Top
        timeLabel.leading(62*widthScale).trailing(90*widthScale)
        timeLabel.Top == nameLabel.Bottom + 1*widthScale
        contentWebView.leading(12*widthScale).trailing(12*widthScale).height(300)
        contentWebView.Top == userView.Bottom + 20*widthScale
        gameView.leading(12*widthScale).trailing(12*widthScale).height(145)
        gameView.Top == contentWebView.Bottom + 5*widthScale
        gameImageView.leading(16*widthScale).top(16*widthScale).size(48*widthScale)
        gameNameLab.leading(75*widthScale).top(20*widthScale).trailing(>=80)
        gameNameTagLab.width(55*widthScale).height(18*widthScale)
        gameNameTagLab.CenterY == gameNameLab.CenterY
        gameNameTagLab.Leading == gameNameLab.Trailing + 3*widthScale
        subLabel.leading(75*widthScale).trailing(80*widthScale)
        subLabel.Top == gameNameLab.Bottom + 4*widthScale
        gameContentLabel.leading(16*widthScale).trailing(16*widthScale)
        gameContentLabel.Top == gameImageView.Bottom + 10*widthScale
        headingLabel.leading(12*widthScale)
        headingLabel.Top == gameView.Bottom + 25*widthScale
        yqwView.leading(0).trailing(0).height(205*widthScale)
        yqwView.Top == headingLabel.Bottom + 20*widthScale
        commitListView.leading(0).trailing(0).height(0).bottom(10)
        commitListView.Top == yqwView.Bottom
        shareButton.snp.makeConstraints { make in
            make.centerY.equalTo(navigationView.titleLabel)
            make.right.equalTo(-10*widthScale)
            make.width.equalTo(44*widthScale)
            make.height.equalTo(44*widthScale)
        }
        
        commitView.isHidden = true
        commitListView.isHidden = true
        containerView.isUserInteractionEnabled = true
        gameView.isUserInteractionEnabled = true
        let tapG = UITapGestureRecognizer(target: self, action: #selector(clickGameView))
        gameView.addGestureRecognizer(tapG)
        
        bottomView.showCommitView = {
            self.bottomView.isHidden = true
            self.commitView.isHidden = false
            self.commitView.commitView.becomeFirstResponder()
        }
        
        bottomView.likeButtonBlock = {
            self.like(type: "0", pid: "\(self.infoId)")
        }
        
        bottomView.collectButtonBlock = {
            self.collect(id: "\(self.infoId)")
        }
        
        commitView.sendTextBlock = { commitStr in
            
            self.httpManager.sendInfoCommit(infoId: "\(self.infoId)", pid: "", content: commitStr) { message in
                self.bottomView.isHidden = false
                self.commitView.isHidden = true
                self.commitView.commitView.resignFirstResponder()
                self.loadCommitListData()
            } failure: { error in
                self.view.showHUD(title: error)
            }

        }
        commitListView.commitDetailVC = { commitID in
            
//            let sonController = HWGameCommentSonController()
//            sonController.id = commitID
//            sonController.gameId = self.gid
//            sonController.releaseCallBack = {
//                self.loadData()
//            }
//            self.navigationController?.pushViewController(sonController, animated: true)
        }
        commitListView.toAllCommitListVC = {
            let allVC = HWInfoDetailAllCommitListVC()
            allVC.infoId = self.infoId
            allVC.gid = self.gid
            self.navigationController?.pushViewController(allVC, animated: true)
        }
        commitListView.likeCommit = { id in
            
        }
    }
    
    @objc private func clickGameView() {
        
        let gameID = self.infoGameModel?.id ?? 0
        if gameID == 584 {
            //黑神话
            self.navigationController?.pushViewController(HWWuKongDetailVC(), animated: true)
        }else{
            let detailVC = HWGameDetailController()
            detailVC.gameId = String(gameID)
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
    
    private func loadHTML(htmlString: String) {
        let resultString = htmlString
            .replacingOccurrences(of: "\"", with: "")
        // 补全 HTML 结构
        let completeHTMLString = """
                    <html>
                    <head>
                        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
                        <style>
                            body { font-family: -apple-system, Arial; font-size: 16px; margin: 0; padding: 0; }
                            iframe { max-width: 100%; height: auto; }
                            img {
                                max-width: 100%;
                                height: auto;
                            }
                        </style>
                    </head>
                    <body>
                        \(resultString)
                    </body>
                    </html>
                    """
                    
                    // 加载 HTML
        contentWebView.loadHTMLString(completeHTMLString, baseURL: nil)
    }
    
    // 当页面加载完成后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // 执行 JavaScript 来计算内容的高度
        webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] result, error in
            if let height = result as? CGFloat {
                // 更新 WebView 高度
                self?.contentWebView.heightConstraint?.constant = height
            }
        }
    }
    
    // 键盘消失时调用的方法
    @objc func keyboardWillHide(_ notification: Notification) {
        guard let userInfo = notification.userInfo else { return }

        self.commitView.isHidden = true
        self.bottomView.isHidden = false
//        self.commitView.topConstraint?.constant = .screenHeight
        self.commitView.commitView.resignFirstResponder()
    }

    @objc private func clickShareButton(){
        
        let shareUrl = self.gameModel?.share_url
        let activityController = UIActivityViewController(activityItems: [shareUrl as Any], applicationActivities: nil)

        self.present(activityController, animated: true, completion: nil)
    }
}


